package com.softa.common.utils;

import com.google.zxing.*;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.softa.common.qrcode.BufferedImageLuminanceSource;
import com.softa.common.qrcode.QrcodeParam;
import com.softa.common.sysconfig.exception.BusinessException;
import org.apache.commons.lang3.StringUtils;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.geom.RoundRectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.Date;
import java.util.Hashtable;
import java.util.Random;

/**
 * 二维码工具类
 *
 * @author 杨磊
 * @date 2019/5/1 23:03
 * @since 1.0
 **/
public class QrCodeUtil {

    private static BufferedImage createImage(QrcodeParam qrcodeParam) throws Exception {
        Hashtable<EncodeHintType, Object> hints = new Hashtable<>();
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
        hints.put(EncodeHintType.CHARACTER_SET, qrcodeParam.getCharset());
        hints.put(EncodeHintType.MARGIN, 1);
        BitMatrix bitMatrix = new MultiFormatWriter().encode(qrcodeParam.getText(),
                BarcodeFormat.QR_CODE, qrcodeParam.getSize(), qrcodeParam.getSize(), hints);
        int width = bitMatrix.getWidth();
        int height = bitMatrix.getHeight();
        BufferedImage image = new BufferedImage(width, height,
                BufferedImage.TYPE_INT_RGB);
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                image.setRGB(x, y, bitMatrix.get(x, y) ? 0xFF000000
                        : 0xFFFFFFFF);
            }
        }
        if (StringUtils.isEmpty(qrcodeParam.getLogoPath())) {
            return image;
        }
        // 插入logo图片
        QrCodeUtil.insertImage(image, qrcodeParam);
        return image;
    }

    /**
     * 插入LOGO
     *
     * @param source 二维码图片
     * @throws Exception
     */
    private static void insertImage(BufferedImage source, QrcodeParam qrcodeParam) throws Exception {
        File file = new File(qrcodeParam.getLogoPath());
        if (!file.exists()) {
            throw new BusinessException("" + qrcodeParam.getLogoPath() + "   该文件不存在！");
        }
        Image src = ImageIO.read(new File(qrcodeParam.getLogoPath()));
        int width = src.getWidth(null);
        int height = src.getHeight(null);
        //压缩LOGO
        if (qrcodeParam.getNeedCompress()) {
            if (width > qrcodeParam.getLogoWidth()) {
                width = qrcodeParam.getLogoWidth();
            }
            if (height > qrcodeParam.getLogoHeight()) {
                height = qrcodeParam.getLogoHeight();
            }
            Image image = src.getScaledInstance(width, height,
                    Image.SCALE_SMOOTH);
            BufferedImage tag = new BufferedImage(width, height,
                    BufferedImage.TYPE_INT_RGB);
            Graphics g = tag.getGraphics();
            //绘制缩小后的图
            g.drawImage(image, 0, 0, null);
            g.dispose();
            src = image;
        }
        // 插入LOGO
        Graphics2D graph = source.createGraphics();
        int x = (qrcodeParam.getSize() - width) / 2;
        int y = (qrcodeParam.getSize() - height) / 2;
        graph.drawImage(src, x, y, width, height, null);
        Shape shape = new RoundRectangle2D.Float(x, y, width, width, 6, 6);
        graph.setStroke(new BasicStroke(3f));
        graph.draw(shape);
        graph.dispose();
    }

    /**
     * 生成二维码(内嵌LOGO), 二维码下面带内容
     *
     * @param qrcodeParam 二维码请求内容
     * @throws Exception
     */
    public static String encode(QrcodeParam qrcodeParam) throws Exception {
        BufferedImage image = QrCodeUtil.createImage(qrcodeParam);
        if (StringUtils.isNotEmpty(qrcodeParam.getWords())) {
            image = insertWords(image, qrcodeParam);
        }
        mkdirs(qrcodeParam.getDestPath());
        String fileName = DateUtils.getyyyyMMddHHmmss(new Date()) + new Random().nextInt(99999) + ".png";
        ImageIO.write(image, qrcodeParam.getFormatName(), new File(qrcodeParam.getDestPath() + "/" + fileName));
        return fileName;
    }

    /**
     * 当文件夹不存在时，mkdirs会自动创建多层目录，区别于mkdir．(mkdir如果父目录不存在则会抛出异常)
     *
     * @param destPath 存放目录
     */
    public static void mkdirs(String destPath) {
        File file = new File(destPath);
        //当文件夹不存在时，mkdirs会自动创建多层目录，区别于mkdir．(mkdir如果父目录不存在则会抛出异常)
        if (!file.exists() && !file.isDirectory()) {
            file.mkdirs();
        }
    }

    /**
     * 解析二维码
     *
     * @param file 二维码图片
     * @return
     * @throws Exception
     */
    public static String decode(File file, QrcodeParam qrcodeParam) throws Exception {
        BufferedImage image;
        image = ImageIO.read(file);
        if (image == null) {
            return null;
        }
        BufferedImageLuminanceSource source = new BufferedImageLuminanceSource(
                image);
        BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
        Result result;
        Hashtable<DecodeHintType, Object> hints = new Hashtable<DecodeHintType, Object>();
        hints.put(DecodeHintType.CHARACTER_SET, qrcodeParam.getCharset());
        result = new MultiFormatReader().decode(bitmap, hints);
        String resultStr = result.getText();
        return resultStr;
    }

    /**
     * 解析二维码
     *
     * @return
     * @throws Exception
     */
    public static String decode(QrcodeParam qrcodeParam) throws Exception {
        File file = new File(qrcodeParam.getDestPath());
        return QrCodeUtil.decode(file, qrcodeParam);
    }

    /**
     * 把带logo的二维码下面加上文字
     *
     * @param image
     * @return
     */
    private static BufferedImage insertWords(BufferedImage image, QrcodeParam qrcodeParam) {
        String words = qrcodeParam.getWords();
        // 新的图片，把带logo的二维码下面加上文字
        if (StringUtils.isNotEmpty(words)) {
            int size = qrcodeParam.getSize();
            // 新的图片，把带logo的二维码下面加上文字
            int heightn = size + qrcodeParam.getOffset();
            BufferedImage outImage = new BufferedImage(size, heightn, BufferedImage.TYPE_INT_ARGB);
            Graphics2D outg = outImage.createGraphics();
            //创建一个带透明色的BufferedImage对象
            setGraphics2D(outg);

            // 画二维码到新的面板
            int height = image.getHeight();
            outg.drawImage(image, 0, 0, image.getWidth(), height, null);

            // 画文字到新的面板
            outg.setColor(Color.black);
            // 字体、字型、字号
            outg.setFont(new Font("宋体", Font.BOLD, 20));
            int strWidth = outg.getFontMetrics().stringWidth(words);
            if (strWidth > qrcodeParam.getSize()) {
                //长度过长就截取前面部分
                // 长度过长就换行
                String note1 = words.substring(0, words.length() / 2);
                String note2 = words.substring(words.length() / 2, words.length());
                int strWidth1 = outg.getFontMetrics().stringWidth(note1);
                int strWidth2 = outg.getFontMetrics().stringWidth(note2);
                outg.drawString(note1, size / 2 - strWidth1 / 2, height + (outImage.getHeight() - height) / 2 + 12);
                heightn = heightn + qrcodeParam.getOffset();
                BufferedImage outImage2 = new BufferedImage(size, heightn, BufferedImage.TYPE_INT_ARGB);
                Graphics2D outg2 = outImage2.createGraphics();
                setGraphics2D(outg2);
                outg2.drawImage(outImage, 0, 0, outImage.getWidth(), outImage.getHeight(), null);
                outg2.setColor(Color.black);
                // 字体、字型、字号
                outg2.setFont(new Font("宋体", Font.BOLD, 20));
                outg2.drawString(note2, size / 2 - strWidth2 / 2, outImage.getHeight() + (outImage2.getHeight() - outImage.getHeight()) / 2 + 5);
                outg2.dispose();
                outImage2.flush();
                outImage = outImage2;
            } else {
                // 画文字
                outg.drawString(words, size / 2 - strWidth / 2, height + (outImage.getHeight() - height) / 2 + 12);
            }
            outg.dispose();
            outImage.flush();
            return outImage;
        }
        return null;
    }

    /**
     * 设置 Graphics2D 属性  （抗锯齿）
     *
     * @param graphics2D
     */
    private static void setGraphics2D(Graphics2D graphics2D) {
        graphics2D.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        graphics2D.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_DEFAULT);
        Stroke s = new BasicStroke(1, BasicStroke.CAP_ROUND, BasicStroke.JOIN_MITER);
        graphics2D.setStroke(s);
    }

    public static void main(String[] args) throws Exception {
        QrcodeParam qrcodeParam = new QrcodeParam();
        qrcodeParam.setText("https://www.baidu.com/");
        qrcodeParam.setLogoPath("D:\\project\\qrcode/222.jpg");
        qrcodeParam.setDestPath("D:\\project\\qrcode");
        qrcodeParam.setWords("这里是百度的地址啊，是真的啊");
        //带logo，二维码下方有文字
        QrCodeUtil.encode(qrcodeParam);
        //不带logo
//        qrcodeParam.setLogoPath(null);
//        QrCodeUtil.encode(qrcodeParam);
        //不带logo，二维码下方无文字
//        qrcodeParam.setLogoPath(null);
//        qrcodeParam.setWords(null);
//        QrCodeUtil.encode(qrcodeParam);
        //带logo，二维码下方无文字
//        qrcodeParam.setWords(null);
//        QrCodeUtil.encode(qrcodeParam);
        //不带logo，二维码下方有文字
//        qrcodeParam.setLogoPath(null);
//        QrCodeUtil.encode(qrcodeParam);
    }

}
